package org.zjsru.gateway;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthorizationFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        String token = request.getHeaders().getFirst("Token");
        
        log.info("请求路径: {}", path);
        log.info("Token值: {}", token);
        
        // 如果路径以/user/public开头，不需要验证token
        if (path.startsWith("/user/public")) {
            log.info("公开接口，无需验证token");
            return chain.filter(exchange);
        }

        // 验证Token
        if ("123456".equals(token)) {
            log.info("Token验证通过");
            return chain.filter(exchange);
        }
        
        // Token无效，返回401
        log.warn("Token验证失败: {}", token);
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
